package file;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class Demo2 extends JFrame implements ActionListener{//监听接口
    private JTextField tf;//文本框，用来显示计算结果
    private JButton clrBtn;//清除按钮

    public Demo2(){
        setTitle("简易计算器");
        setVisible(true);
        setSize(400,300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel1=new JPanel();
        JPanel panel2=new JPanel();
        tf=new JTextField();
        panel1.setLayout(new BorderLayout());
        panel1.add(tf);
        clrBtn=new JButton("清除");
        panel1.add(clrBtn,BorderLayout.EAST);
        add(panel1,BorderLayout.NORTH);
        panel2.setLayout(new GridLayout(4,4));
        String[] str={"7","8","9","+","4","5","6","-","1","2","3","*","0",".","=","/"};
        for (String s:str){
            JButton bt=new JButton(s);
            bt.addActionListener(this);//把bt添加到监听器里
            panel2.add(bt);
        }
        add(panel2);
    }

    public static void main(String[] agrs){
       SwingUtilities.invokeLater(new Runnable() {
           @Override
           public void run() {
               new Demo2();
           }
       });
    }

    @Override//Ctrl+i 实现监听函数
    public void actionPerformed(ActionEvent e) {
        String s=e.getActionCommand();
        tf.setText(tf.getText()+s);
        JOptionPane.showMessageDialog(this,s);
    }

}
